package cn.ygh.bbo.framerwork.aspect;

import cn.ygh.bbo.common.exception.JsonException;
import cn.ygh.bbo.common.exception.LoginException;
import cn.ygh.bbo.common.exception.TipException;
import cn.ygh.bbo.framerwork.core.ResultAjax;
import cn.ygh.bbo.framerwork.web.WebUtils;
import cn.ygh.bbo.framerwork.web.editor.BigDecimalPropertyEditorSupport;
import cn.ygh.bbo.framerwork.web.editor.DatePropertyEditorSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;

/**
 * @author ygh
 * @Desc 全局通用异常处理 及 配置配置
 * 统一异常 和 mvc 配置
 * 401未登陆
 * 403通用异常弹窗 406自定义异常弹窗
 * 需要处理的话通过json code
 * @date 2018/7/1 22:28
 */
@ControllerAdvice
public class ControllerHandler {

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 全局api配置绑定
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        // Date 类型转换
        binder.registerCustomEditor(Date.class, new DatePropertyEditorSupport());
        //BigDecimal 类型转换
        binder.registerCustomEditor(BigDecimal.class, new BigDecimalPropertyEditorSupport());
    }
    /**
     * 通用异常拦截
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(value = {Exception.class})
    @ResponseBody
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public final String handleDefException(Exception ex) {
        printfError(ex.getMessage());
        return ex.getMessage();
    }

    /**
     * 该异常 前端会弹窗
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(value = {TipException.class})
    @ResponseBody
    @ResponseStatus(HttpStatus.NOT_ACCEPTABLE)
    public final String handleBoException(TipException ex) {
        printfError(ex.getMessage());
        return ex.getMessage();
    }

    /**
     * 没有登陆异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(value = {LoginException.class})
    @ResponseBody
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public final String handleNeedLoginException(LoginException ex) {
        printfError(ex.getMessage());
        return ex.getMessage();
    }

    /**
     * 正常的异常  只是为了程序中断 前端不做任何处理
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(value = {JsonException.class})
    @ResponseBody
    public final ResultAjax handleRightException(JsonException ex) {
        printfError(ex.getMessage());
        return ResultAjax.fail(ex.getCode(), ex.getMessage());
    }

    /**
     * 错误日志打印
     *
     * @param error
     */
    private void printfError(String error) {
        //权限通过 记录一下日志
        String uri = WebUtils.getUri();
        String ip = WebUtils.getIp();
        String msg = String.format("uri :%s ip:%s error: %s", uri, ip, error);
        logger.error(msg);
    }



}
